<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Signing Reset (Reset Password)
 * @description : Generate a new password and email it to user
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Reset_password extends MY_Controller {

  public function __construct() {
    parent::__construct();
    $signuser = $this->user_session->signuser();
    if ($signuser) {
      redirect('tweets');
      return;
    }
  }

  public function index() {
    $reset_status = NULL;
    if ($this->is_post()) {
      $reset_status = 2;
      $inno_email = trim($this->input->post('inno_email', TRUE));
      $inno_email_confirm = trim($this->input->post('inno_email_confirm', TRUE));
      if (!empty($inno_email) && ($inno_email == $inno_email_confirm) && filter_var($inno_email, FILTER_VALIDATE_EMAIL)) {
        $email_data = explode('@', $inno_email);
        if (!empty($email_data) && is_array($email_data) && end(($email_data)) == 'innovaturelabs.com') {
          $reset_status = 3;
          $user_name = reset($email_data);
          $user_password = $this->sanitize('innovature' . rand(111, 999));
          $get_user_by_username = $this->user_model->get_user_by_username($user_name);
          if (!empty($user_name) && !empty($get_user_by_username['result'])) {
            $user_id = $get_user_by_username['result']['user_id'];
            $user_update_data['user_password'] = md5($user_password);
            $update_profile = $this->user_model->update_profile($user_id, $user_update_data);
            if ($update_profile['status'] == 1 && !empty($update_profile['result'])) {
              $reset_status = 1;
              $log_msg = $user_name . ' (' . $inno_email . ') ' . 'from ' . $this->input->ip_address() . ' on ' . $this->agent->platform() . ' ' . $this->agent->browser() . ' ' . $this->agent->version();
              system_log('reset_password', $log_msg);
              $this->send_email($user_name, $user_password, $inno_email);
            }
          }
        }
      } else {
        $reset_status = 4;
      }
      $this->session->set_flashdata('reset_status', $reset_status);
      redirect('reset_password');
      return;
    }
    $view_data = array();
    $this->load_view('reset_password', $view_data);
    return;
  }

  private function send_email($user_name = NULL, $password = NULL, $user_email = NULL) {
    $msg = "Username : {$user_name}<br/><br/>Password : {$password}<br/>";
    $this->load->library('email');
    $this->email->clear(TRUE);
    $this->email->set_mailtype("html");
    $this->email->from('innotweets@gmail.com', 'innoTweets');
    $this->email->to($user_email);
    $this->email->subject('innoTweets : Password Reset');
    $this->email->message($msg);
    $this->email->send();
    return;
  }

}

?>
